package com.cskaoyan._02sync;

/**
 * @description:
 * @author: 景天
 * @date: 2023/2/22 10:52
 **/
/*
同步代码块
synchronized(锁对象){
    // 对于共享数据的操作
}
锁对象可以是任意的java对象, 但是要保证是同一个
 */
public class Demo {
    public static void main(String[] args) {
        SellWindow sellWindow = new SellWindow();
        new Thread(sellWindow, "A窗口").start();
        new Thread(sellWindow, "B窗口").start();
        new Thread(sellWindow, "C窗口").start();
    }
}

class SellWindow implements Runnable{

    int tickets = 100;

    // 定义一把锁
    //A lock = new A();
    // B lock = new B();
    Object lock = new Object();

    @Override
    public void run() {
        while (true) {
            // 使用同步代码块
            synchronized (lock) {
                if (tickets > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    System.out.println(Thread.currentThread().getName() + "卖了第"
                            + (tickets--) + "张票");
                }
            }

        }
    }
}

class A{}

class B{}